package com.jastar.android.game.richman.logic.handler;

import com.jastar.android.game.richman.GameActivity;
import com.jastar.android.game.richman.logic.Event.BaseEvent;
import com.jastar.android.game.richman.logic.Event.Event;
import com.jastar.android.game.richman.logic.GameManager;
import com.jastar.android.game.richman.logic.bean.Cell;
import com.jastar.android.game.richman.logic.bean.Player;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class CellDisasterHandler extends CellEventHandler {

    @Override
    protected void initEvents(List<Event> events) {

        //个人升级
        events.add(new BaseEvent("政府补贴，随机升级一处你的房产.", 6, (a, c, p) -> Cell.randomLevelup(1, p)));
        //随机升级
        events.add(new BaseEvent("城市扩建，随机升级3处房产.", 2, (a, c, p) -> Cell.randomLevelup(3, null)));
        //随机摧毁
        events.add(new BaseEvent("发生地震，随机摧毁3处房产.", 1, (a, c, p) -> Cell.randomDestroy(3)));
        //救济
        events.add(new BaseEvent("政府救济，最穷的玩家获得现金：3", 1, this::relief));
        //征税
        events.add(new BaseEvent("政府征房产税，每个玩家缴纳一半房产数的现金.", 2, this::buildingTaxes));
    }

    /** 救济 */
    private void relief(GameActivity activity, Cell cell, Player player) {
        GameManager manager = activity.getManager();
        AtomicInteger min = new AtomicInteger(Integer.MAX_VALUE);
        manager.getPlayers().forEach(p -> min.set(Math.min(min.get(), p.getMoney())));
        manager.getPlayers().stream().filter(p -> p.getMoney() == min.get()).forEach(p -> p.receive(3));
    }

    /** 征税 */
    private void buildingTaxes(GameActivity activity, Cell cell, Player player) {
        GameManager manager = activity.getManager();
        Map<String, Integer> playerLandCount = new HashMap<>();
        manager.getCells().stream().filter(c -> null != c.getOwner()).forEach(c -> {
            String key = c.getOwner().getName();
            playerLandCount.put(key, playerLandCount.containsKey(key) ? playerLandCount.get(key) + 1 : 1);
        });
        manager.getPlayers().forEach(p -> {
            String key = p.getName();
            if (playerLandCount.containsKey(key)) {
                p.payUntilZero(playerLandCount.get(key) / 2);
            }
        });
    }

}
